<!-- 登录 -->
<template>
  <view>
    <view class="login-container">
      <view style="height: 70px">&nbsp;</view>
      <view class="logo-container">
        <img class="logo" src="../../static/images/logo.png" />
      </view>
      <view class="app-name">Aster</view>
      <view class="login-content">
        <view class="content-field" v-if="tenantVisible">
          <view class="field-label">租户</view>
          <view class="field-item">
            <view class="field-icon">
              <span class="iconfont icon-navicon-zhgl"></span>
            </view>
            <view class="field-content">
              <van-field
                v-model="selectedTenantName"
                is-link
                readonly
                name="picker"
                placeholder="点击选择租户"
                @click="showTenant = true"
              />
              <van-popup v-model:show="showTenant" destroy-on-close position="bottom">
                <van-picker
                  :columns="tenantList"
                  :model-value="selectedTenantValue"
                  :columns-field-names="{ text: 'companyName', value: 'id' }"
                  @confirm="handleTenantConfirm"
                  @cancel="showTenant = false"
                />
              </van-popup>
            </view>
          </view>
        </view>
        <view class="content-field">
          <view class="field-label">用户名</view>
          <view class="field-item">
            <view class="field-icon">
              <span class="iconfont icon-yonghu"></span>
            </view>
            <view class="field-content">
              <van-field
                v-model="loginForm.username"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '用户名不能为空' }]"
                :clearable="true"
              />
            </view>
          </view>
        </view>
        <view class="content-field">
          <view class="field-label">密码</view>
          <view class="field-item">
            <view class="field-icon">
              <span class="iconfont icon-mima"></span>
            </view>
            <view class="field-content">
              <van-field
                type="password"
                v-model="loginForm.password"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '密码不能为空' }]"
                :clearable="true"
              />
            </view>
          </view>
        </view>
        <view class="content-field" v-if="captchaVisible">
          <view class="field-label">验证码</view>
          <view class="field-item">
            <view class="field-icon">
              <span class="iconfont icon-yanzhengma"></span>
            </view>
            <view class="field-content">
              <view style="display: flex" class="justify-center items-center">
                <van-field v-model="loginForm.captcha" placeholder="请输入验证码" />
                <img :src="captchaBase64" @click="onCaptcha" />
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="operation-container">
        <van-button type="primary" size="large" :round="true" @click="submit">登录</van-button>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app';
  import { HideLoading, Loading, Toast } from '@/utils/uniapi/prompt';
  import { reactive, ref } from 'vue';
  import { router } from '@/utils/router';
  import { isEmpty } from '@/utils/is';
  import config from '@/utils/config';
  import { useUserStore } from '@/store/modules/user';
  import { useAppStore } from '@/store/modules/app';
  import { useTenantStore } from '@/store/modules/tenant';
  import { encrypt } from '@/utils/encrypt';
  import {
    captchaApi,
    captchaEnabledApi,
    loginApi,
    tenantEnabledApi,
    tenantListApi,
    userInfoApi,
  } from '@/api/login';

  const userStore = useUserStore();
  const appStore = useAppStore();
  const tenantStore = useTenantStore();

  // 秘钥
  const secretKey = ref('');
  // 是否显示租户
  const tenantVisible = ref(false);
  const tenantList = ref<Tenant.TenantInfo[]>([]);
  const showTenant = ref(false);
  const selectedTenantName = ref('');
  const selectedTenantValue = ref([]);
  // 是否显示验证码
  const captchaVisible = ref(false);
  const captchaBase64 = ref();

  /** 待提交参数 */
  const loginForm = reactive<Login.ReqLoginForm>({
    username: 'admin',
    password: '123456',
    key: '',
    captcha: '',
    tenantId: '000000',
  });

  /** 租户选择 */
  const handleTenantConfirm = ({ selectedValues, selectedOptions }) => {
    loginForm.tenantId = selectedOptions[0]?.id;
    selectedTenantName.value = selectedOptions[0]?.companyName;
    selectedTenantValue.value = selectedValues;
    showTenant.value = false;
  };

  /** 表单校验 */
  const validateForm = () => {
    if (isEmpty(loginForm.username)) {
      Toast('请输入用户名');
      return false;
    }
    if (isEmpty(loginForm.password)) {
      Toast('请输入密码');
      return false;
    }
    if (captchaVisible.value && isEmpty(loginForm.captcha)) {
      Toast('请输入验证码');
      return false;
    }
    return true;
  };

  /** 登录 */
  const submit = async () => {
    const validate = validateForm();
    if (!validate) return;
    // 密码加密
    // queryParams.password = encryptByMd5(password.value);
    Loading('');
    try {
      // 1.加密密码
      const encryptPassword = encrypt(loginForm.password, secretKey.value);

      // 2.执行登录接口
      const { data } = await loginApi({ ...loginForm, password: encryptPassword });
      userStore.setToken(data.access_token);

      // 3.获取登录人信息
      const res = await userInfoApi();
      userStore.setUserInfo(res.data);

      // 4.添加字典
      await appStore.setDictList();

      // 5.跳转到首页
      router.reLaunch(config.route.home);
    } catch {
      if (captchaVisible.value) {
        onCaptcha();
      }
    } finally {
      HideLoading();
    }
  };
  /**
   * @description: 密钥
   * @return {*}
   */
  const getSecretKey = async () => {
    secretKey.value = appStore.secretKey;
  };

  /**
   * @description: 获取验证码
   * @return {*}
   */
  const onCaptcha = async () => {
    const { data } = await captchaApi();
    loginForm.key = data.key;
    captchaBase64.value = data.image;
  };

  /**
   * @description: 是否开启租户
   * @return {*}
   */
  const onTenantEnabled = async () => {
    const { data } = await tenantEnabledApi();
    tenantVisible.value = data;
    tenantStore.setEnabled(tenantVisible.value);
    // 若开启，则获取租户列表
    if (tenantVisible.value) {
      tenantListApi().then(({ data }) => {
        tenantList.value = data;
        tenantStore.setTenantList(tenantList.value);
      });
    }
  };

  /**
   * @description: 是否开启验证码
   * @return {*}
   */
  const onCaptchaEnabled = async () => {
    const { data } = await captchaEnabledApi();
    captchaVisible.value = data;

    if (data) {
      await onCaptcha();
    }
  };

  onLoad(async () => {
    // 租户
    await onTenantEnabled();
    // 验证码
    await onCaptchaEnabled();
    // 获取秘钥
    await appStore.setSecretKey();
    await getSecretKey();
  });
</script>
<style lang="scss" scoped>
  .login-container {
    width: 100%;
    height: 100vh;
    // margin: 0 auto;
    text-align: center;
    background-color: #ffffff;
    background-image: url('~@/static/images/login-bg.png');
    background-size: 100%;

    .logo-container {
      width: 160rpx;
      height: 160rpx;
      margin: 0 auto;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      .logo {
        width: 100%;
      }
    }

    .app-name {
      width: 100%;
      text-align: center;
      color: #263044;
      font-size: 60rpx;
      font-weight: bold;
      margin-top: 30rpx;
    }

    .content-field {
      width: 90%;
      margin: 0 auto;
    }

    .field-label {
      width: 100%;
      text-align: left;
      font-size: 30rpx;
      color: #263044;
      padding: 20rpx 0rpx;
      font-weight: bold;
    }

    .field-item {
      width: 100%;
      display: flex;
      border: 1px solid #e5e5e5;
      padding: 12rpx 20px;
      border-radius: 40rpx;
      .field-icon {
        width: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 35rpx;
        font-weight: bold;
      }
      .field-content {
        flex: 1;
      }
    }

    .operation-container {
      width: 90%;
      margin: 0 auto;
      margin-top: 100rpx;
      text-align: center;
    }

    .iconfont {
      font-weight: bold;
    }

    .van-field {
      background-color: #fafafa;
    }

    ::v-deep .van-field__control {
      font-size: 30rpx;
    }
  }
</style>
